package cn.brondfish.icedfish.ui.home.setting;

import android.app.AlertDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowInsetsController;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.app.AppCompatDelegate;
import androidx.core.content.ContextCompat;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.lifecycle.ViewModelProvider;

import com.google.android.material.navigation.NavigationView;

import java.util.Arrays;

import cn.brondfish.icedfish.MainActivity;
import cn.brondfish.icedfish.R;
import cn.brondfish.icedfish.common.Constants;
import cn.brondfish.icedfish.framework.option.AppThemeEnum;
import cn.brondfish.icedfish.ui.home.setting.server.ServerSettingActivity;

public class AppSettingActivity extends AppCompatActivity {

    private AppThemeEnum[] app_theme_options = null;
    private AlertDialog appThemeDialog;
    private AppSettingViewModel dashboardViewModel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setTheme(R.style.Theme_IcedFish);
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_app_setting);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.app_setting_activity), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
            actionBar.setCustomView(R.layout.app_action_bar);
            final LinearLayout app_action_bar = findViewById(R.id.app_action_bar);
            ImageButton back_before_activity_button = app_action_bar.findViewById(R.id.back_before_activity_button);
            ImageButton back_home_activity_button = app_action_bar.findViewById(R.id.back_home_activity_button);
            TextView activity_title = app_action_bar.findViewById(R.id.activity_title);
            back_before_activity_button.setOnClickListener(view -> {
                finish();
            });
            back_home_activity_button.setOnClickListener(view -> {
                Intent intent = new Intent(this, MainActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                startActivity(intent);
            });
            activity_title.setText(getString(R.string.title_activity_app_setting));
        }
        initStyle();
        initDateModule();
        initMenu();
    }


    private void initMenu() {
        final NavigationView app_setting_menu = findViewById(R.id.app_setting_menu);
        app_setting_menu.setNavigationItemSelectedListener(item->{
            int itemId = item.getItemId();
            if (itemId == R.id.setting_item_app_theme) {
                showThemeDialog();
                return true;
            }
            if (itemId == R.id.setting_item_app_server) {
                Intent intent = new Intent(this, ServerSettingActivity.class);
                startActivity(intent);
                return true;
            }
            return false;
        });
    }

    private void showThemeDialog() {
        if (appThemeDialog != null && appThemeDialog.isShowing()) {
            appThemeDialog.dismiss();
        }
        String cfg_app_theme_key;
        cfg_app_theme_key = dashboardViewModel.getApp_theme().getValue();
        if(cfg_app_theme_key == null || cfg_app_theme_key.isEmpty()){
            cfg_app_theme_key = AppThemeEnum.AUTO.getKey();
        }
        int defaultItem = -1;
        for (int index = 0; index < app_theme_options.length; index++){
            if(app_theme_options[index].getKey().equals(cfg_app_theme_key)) {
                defaultItem = index;
                break;
            }
        }
        String[] app_theme_option_texts = Arrays.stream(app_theme_options).map(option->getString(option.getValue())).toArray(String[]::new);
        AlertDialog.Builder builder = new AlertDialog.Builder(AppSettingActivity.this);
        builder.setTitle(getString(R.string.setting_app_theme_select_label));
        builder.setSingleChoiceItems(app_theme_option_texts,defaultItem,(dialog,which)->{
            AppThemeEnum app_themeOption = app_theme_options[which];
            dashboardViewModel.getApp_theme().setValue(app_themeOption.getKey());
            dashboardViewModel.saveConfig();
            // 保存主题设置到APP
            int currentNightMode = AppCompatDelegate.getDefaultNightMode();
            int targetNightMode;
            switch (app_themeOption) {
                case DARK:
                    targetNightMode = AppCompatDelegate.MODE_NIGHT_YES;
                    break;
                case LIGHT:
                    targetNightMode = AppCompatDelegate.MODE_NIGHT_NO;
                    break;
                default:
                    targetNightMode = AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM;
                    break;
            }
            if (currentNightMode != targetNightMode) {
                SharedPreferences sharedPreferences = getSharedPreferences(Constants.PREFS_NAME, MODE_PRIVATE);
                SharedPreferences.Editor editor = sharedPreferences.edit();
                editor.putInt(Constants.NIGHT_MODE, targetNightMode);
                editor.apply();
                AppCompatDelegate.setDefaultNightMode(targetNightMode);
                recreate();
            }
        });

        // 添加取消按钮
        builder.setNegativeButton("Cancel", (dialog, which) -> dialog.cancel());

        // 创建并显示对话框
        appThemeDialog = builder.create();
        appThemeDialog.show();
    }

    private void initDateModule() {
        app_theme_options = AppThemeEnum.getIds();
        dashboardViewModel = new ViewModelProvider(this,new AppSettingViewModelFactory(getApplicationContext())).get(AppSettingViewModel.class);
    }

    public void initStyle() {
        // 设置状态栏颜色
        Window window = getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        window.setStatusBarColor(ContextCompat.getColor(this, R.color.black));
        // 设置状态栏文字和图标颜色
        // 设置状态栏文字和图标颜色为白色
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            window.setDecorFitsSystemWindows(false);
            WindowInsetsController controller = window.getInsetsController();
            if (controller != null) {
                controller.setSystemBarsAppearance(0, WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS);
            }
        } else {
            // 使用旧版本的方式设置状态栏文字和图标颜色
            View decorView = window.getDecorView();
            decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
        }
    }

    @Override
    protected void onDestroy() {
        if (appThemeDialog != null && appThemeDialog.isShowing()) {
            appThemeDialog.dismiss();
        }
        super.onDestroy();
    }
}